package org.project.controller2;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.annotations.Param;
import org.project.pojo.Doreport;
import org.project.pojo.Download;
import org.project.pojo.Download0;
import org.project.pojo.Fit;
import org.project.pojo.Order;
import org.project.pojo.Orderrecord;
import org.project.pojo.Orderrecord2;
import org.project.pojo.Ordertime2;
import org.project.pojo.Outtime;
import org.project.pojo.Remaintimes;
import org.project.pojo.State;
import org.project.pojo.Times;
import org.project.pojo.TypeDetail;
import org.project.service.user.ImgsService;
import org.project.service.user.Order1Service;
import org.project.service.user.OrdertimeService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;



@Controller
@RequestMapping("/ordercontroller")
public class Ordercontroller {
	
	@Resource
	private ImgsService imgsService;
	
	@Resource
	private Order1Service order1Service;
	
	@Resource
	private OrdertimeService ordertimeService;

	
	
	
	@RequestMapping("/orderdo")
	@ResponseBody
	public Order orderdo(@Param("listtime")String listtime,
		@Param("openid")String openid){
        Order order=new Order();
		HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		String shopName=req.getParameter("shopName");
		order.setShopName(shopName);  
		String orderTime=req.getParameter("orderTime");
		order.setOrderTime(orderTime);		
	
		String price=req.getParameter("price");
		order.setPrice(price);
		String prepayPrice=req.getParameter("prepayPrice");
		order.setPrepayPrice(prepayPrice);
		Double balPrice1=Double.parseDouble(price)-Double.parseDouble(prepayPrice);
		String balPrice=String.valueOf(balPrice1);
		order.setBalPrice(balPrice);
	//	State state1=new State();
		
		//生成订单号
		Date date = new Date();
		SimpleDateFormat sim = new SimpleDateFormat("yyyyMMdd");
		String time = sim.format(date);
	//	int x=(int)(Math.random()*900)+100;  
		
		//http://192.168.1.33/weixin/ordercontroller/orderdo?listtime=2018-1-30&openid=oHE4j0fWSOMM5z51g2cQ4Yr-d3YM&shopName=中海环宇城店&orderTime=2017-12-33 16:30&price=153&prepayPrice=20
		
		
		int flag0 = new Random().nextInt(999999);  
	      if (flag0 < 100000)  
	    {  
	        flag0 += 100000;  
	    }  
		String flag=String.valueOf(flag0);
		
		String data = time + flag;
		
		
		order.setOrderid(data);
		order.setOpenid(openid);
		order.setListtime(listtime);
		order.setState("未支付");		
		
		Outtime outtime=new Outtime();
		outtime.setOrderid(data);
		Date outime0=null;
		try {
			outime0 = timeChaange(listtime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		String outtime1=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(outime0);
		outtime.setOutTime(outtime1);
		int j=order1Service.insertouttime(outtime);//向过期表中插入数据
		
		
		
		
		//将字符串转化为真实 typedetaillist
				String typedetaillist1=req.getParameter("typedetaillist");
				
				JSONArray arr=JSONArray.fromObject(typedetaillist1);
				
				System.out.println(arr);
				System.out.println(arr);
				System.out.println(arr);
				List<TypeDetail> typedetaillist=new ArrayList<TypeDetail>();
 	 	
				
				for(Object obj:arr){
				     TypeDetail typeDetail=new TypeDetail();
                     JSONObject json=JSONObject.fromObject(obj);
				 
					 typeDetail.setFunctionName(json.getString("functionName")) ;
					 typeDetail.setName(json.getString("name"));
					 typeDetail.setOrderid(data);
					 typedetaillist.add(typeDetail);
				 }
				 
				
				 
				 
				 
				 
				 
	//开始向数据库插入订单	
		int i=imgsService.insertorder(order); 
	    if(i>0&&j>0){
			Iterator<TypeDetail> it=typedetaillist.iterator();
			while(it.hasNext()) {
				TypeDetail typeDetail=it.next();
				typeDetail.setOrderid(order.getOrderid());
				imgsService.inserttypedetail(typeDetail);//插入完毕
			
				
				
				
				 //  对 操作时间表，剩余时间表     进行操作
				String name=typeDetail.getName();
				int fitnum=ordertimeService.selfitnumbyname(name);
				
				Ordertime2 Ordertime2=counttime(orderTime,fitnum);//包含 操作日期、预约时间、预约结束时间
				
				int shopid=ordertimeService.selshopid(shopName);
				
				 //查询剩余时间表（remaintimes）是否有当天的数据   
				List<String> list=selectremaintimes(shopid,Ordertime2.getDate());
				
				
				if(list.size()==0){//剩余时间表里没有当天此店铺的信息
					Times times=new Times();
					times.setId(Integer.valueOf(shopid));
					Times time0=ordertimeService.selectalltime(times);
					String ordertimes=time0.getOrdertimes(); 
					  String arr2[]=ordertimes.split(",");
					  for(int a=0;a<arr2.length;a++){
						  String time2=arr2[a];
						  Remaintimes remaintimes=new Remaintimes(0,shopid,Ordertime2.getDate(),time2);
						  ordertimeService.insertremaintimes(remaintimes);
					  }//剩余时间表中已插入完整时间信息
				
				
				}
				
				
				
				//再次拿到 剩余时间表中的 当天，该店铺的所有剩余时间
				List<String> list2=selectremaintimes(shopid,Ordertime2.getDate());
				
				//便利剩余时间表
				Iterator<String> it2=list2.iterator();
				while(it2.hasNext()){
					String time4=it2.next();
					Date time5=null;
					try {
						 time5=new SimpleDateFormat("HH:mm").parse(time4);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					if(null!=time5){
						  if((time5.before(Ordertime2.getEndtime())&&time5.after(Ordertime2.getOrdertime()))||time5.equals(Ordertime2.getOrdertime())){
							  //执行修改(剩余时间表)
							  Remaintimes Remaintimes=new Remaintimes(0,shopid,Ordertime2.getDate(),time4);
							  
							  ordertimeService.orderremaintime(Remaintimes);
							    
						  }
						}
					
					
				}
				
				
				
				//向操作表中插入操作数据
				SimpleDateFormat sim2=new SimpleDateFormat("HH:mm");
				String time6=sim2.format(Ordertime2.getOrdertime());
				Doreport Doreport=new Doreport(0,shopid,Ordertime2.getDate(),time6,"预约");
				ordertimeService.insertdoreport(Doreport);
				
				}
           }
		
		          return order;
	
	}
	
	
	
	
	
	
	 
	
	
	
	@RequestMapping("/insertorder2")
	@ResponseBody
	public State insertorder2(@Param("openid")String orderid,@Param("userName")String userName,@Param("phone")String phone,
			@Param("sex")String sex,@Param("birthday")String birthday){
		State state=new State();
		state.setState(0);
		Order order=new Order();
		order.setUserName(userName);
		order.setPhone(phone);
		order.setSex(sex);
		order.setBirthday(birthday);
		order.setOrderid(orderid);
		int i=imgsService.insertorder2(order);
		if(i>0){
			state.setState(1);
		}
		return state;
	}
	
	
	
	
	@RequestMapping("/selectorder")
	@ResponseBody
	public List<Orderrecord>selectorder(@Param("openid")String openid){
		List<Orderrecord> list=imgsService.selectorder(openid);//得到opid对应的订单集合
		List<Orderrecord> list3=new ArrayList<Orderrecord>();
		if(null!=list){
			Iterator<Orderrecord> it = list.iterator();     //遍历订单集合
			while(it.hasNext()) {
				Orderrecord orderrecord=(Orderrecord)it.next();   //集合中的一个对象
				List<TypeDetail>list2=imgsService.selecttypedetails(orderrecord);//由对象的openid获取到商品列表
				if(null!=list2){
				orderrecord.setTypedetaillist(list2);   //将商品列表加入到对象属性中
				list3.add(orderrecord);
				}
				
			}
		}
		
		return list3;
	}
	
	 
	
	
	@RequestMapping("/cancelorder")
	@ResponseBody
	public State cancelorder(@Param("orderid")String orderid){
		   State state=new State();
		   state.setState(0);
		int i=imgsService.cancelorder(orderid);
		int j=order1Service.deleteouttime(orderid);//删除过期数据
		
		
		//通过orderid得到 预约时间
		Order Order=order1Service.selectorder1(orderid);
		String orderTime=Order.getOrderTime();
		String shopName=Order.getShopName();
		//店铺id
		int shopid=ordertimeService.selshopid(shopName);
		
		//得到预约项目的fitnum
		int fitnum=ordertimeService.selorderfitnum(orderid);
		
		Ordertime2 Ordertime3=counttime(orderTime,fitnum);//包含 操作日期、预约时间、预约结束时间
		
		
		//拿到 剩余时间表中的 当天，该店铺的被预约的时间
		List<String> list2=selectdeletedtimes(shopid,Ordertime3.getDate());
		
		//便利剩余时间表
		Iterator<String> it2=list2.iterator();
		while(it2.hasNext()){
			String time4=it2.next();
			Date time5=null;
			try {
				 time5=new SimpleDateFormat("HH:mm").parse(time4);
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(null!=time5){
				  if((time5.before(Ordertime3.getEndtime())&&time5.after(Ordertime3.getOrdertime()))||time5.equals(Ordertime3.getOrdertime())){
					  //执行修改(剩余时间表)
					  Remaintimes Remaintimes=new Remaintimes(0,shopid,Ordertime3.getDate(),time4);
					  
					  ordertimeService.cancelremaintime(Remaintimes);
					    
				  }
				}
			
			
		}
		
		//删除操作表记录
		SimpleDateFormat sim2=new SimpleDateFormat("HH:mm");
		String time6=sim2.format(Ordertime3.getOrdertime());
		Doreport Doreport=new Doreport(0,shopid,Ordertime3.getDate(),time6,null);
		ordertimeService.deletedoreport(Doreport);
		
		
		
		
		
		
		
		
		
		
		
		if(i>0&&j>0){
			 state.setState(1);
		}
		return state;
	}
	
	 
	/*	@RequestMapping("/outtimeorder")
		@ResponseBody
		public State outtimeorder(@Param("orderid")String orderid){
			 State state=new State();
			   state.setState(0);
			 Order order=  order1Service.selectorder1(orderid);
			 String state1=order.getState();
			
			 if(state1.equals("未支付")){
			 
			int i=imgsService.outtimeorder(orderid);
			if(i>0){
				 state.setState(1);
			}
			
			 }
			
			
			return state;
		}
		*/
	
		@RequestMapping("/selectwzforder")
		@ResponseBody
		public State selectwzforder(@Param("openid")String openid){
			State state=new State();
			Order order=imgsService.selectwzforder(openid);
			if(null!=order){
				state.setState(1);
			}else{
				state.setState(0);
			}
			
			return state;
		}
	
		
		
		
		
		@RequestMapping("/selectwcorder1")
		@ResponseBody
		public List<Orderrecord2> selectwcorder1(@Param("openid")String openid){
			
			List<Orderrecord2> list=order1Service.selectwcorder2(openid);//得到opid对应的订单集合
			List<Orderrecord2> list3=new ArrayList<Orderrecord2>();
			if(null!=list){
				Iterator<Orderrecord2> it = list.iterator();     //遍历订单集合
				while(it.hasNext()) {
					Orderrecord2 orderrecord2=(Orderrecord2)it.next();   //集合中的一个对象
					Orderrecord orderrecord=new Orderrecord();
					orderrecord.setOrderid(orderrecord2.getOrderid());
					List<TypeDetail>list2=imgsService.selecttypedetails(orderrecord);//由对象的orderid获取到商品列表
					if(null!=list2){
					orderrecord2.setTypedetaillist(list2);   //将商品列表加入到对象属性中
					list3.add(orderrecord2);
					}
					
				}
			}
			
			return list3;
			
	}


		
		
		@RequestMapping("/seephoto")
		@ResponseBody
		public List<Download> seephoto(@Param("orderid")String orderid){
			List<Download0>list=order1Service.seephoto(orderid);
	//		HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
			String path="https://www.sgdpy.com/"+"download//";
			List<Download> list2=new ArrayList<Download>();//
			if(list!=null){
	    		Iterator<Download0> it = list.iterator();
	    		while(it.hasNext()) {
	    			Download0 download0=it.next();
	    			Download download=new Download();
	    			download.setId(download0.getId());
	    			download.setOrderid(download0.getOrderid());
	    			download.setUrl(path+download0.getImgName());
	    			download.setSuburl(path+download0.getSubimgName());
	    			download.setUploadTime(download0.getUploadTime());
	    			list2.add(download);
	    		}
	    		}
			
			     return list2;
		}
		
		
		
		
		
		/*  @RequestMapping("/checkorderTime")
		  @ResponseBody
		  public List<String> checkorderTime(@Param("shopName")String shopName,@Param("date")String date){
			  Ordertime1 ordertime1=new Ordertime1();
			  ordertime1.setShopName(shopName);
			  ordertime1.setOrderDate(date);
			  
			  List<String> timelist=order1Service.selectorderTime(ordertime1);
			  List<String> timelist2=new ArrayList<String>();
			  Iterator<String> it=timelist.iterator();
			  while(it.hasNext()){
				 
				  
				  String arr[]=it.next().split(" ");
				  String time=arr[1];
				  timelist2.add(time);
			  }
			  return timelist2;
			  
		  }
		*/
		
		
		  
		
		
		  
		
		  
		
		
		
		
		
		
		
		
		
		
		
		
		  public static String getLoaclURL(HttpServletRequest request) {
		    	
				String path_now = request.getContextPath();
				return request.getScheme() + "://" + request.getServerName() + ":"
						+ request.getServerPort() + path_now + "/";
			}
		    
		  
		 //计算15分钟之后
		  public static Date timeChaange (String timeStr) throws ParseException {
			  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			  Date time = sdf.parse(timeStr);
			  Calendar cal = Calendar.getInstance();
			  cal.setTime(time);
			  cal.add(Calendar.MINUTE, +14);
			  time = cal.getTime();
			  return time;
		}
		
	    
		  
		  
			//通过shopid，详细日期  查询剩余时间
			public List<String> selectremaintimes(int shopid,String date){
			   
				Remaintimes remaintimes1=new Remaintimes(0,shopid,date,null);
				List<String> remaintimeslist=ordertimeService.selectremaintimes(remaintimes1);
			  
			    	
				return remaintimeslist;
				
			}
			
		  
		  
		  
		  //通过shopid，详细日期 查询已被预约的时间
			public List<String> selectdeletedtimes(int shopid,String date){
				Remaintimes remaintimes1=new Remaintimes(0,shopid,date,null);
				List<String> deletedlist=ordertimeService.selectyuyuedtimes(remaintimes1);
				
				return deletedlist;
			}
		  
		  
		  
		  
		  public  Ordertime2   counttime(String orderTime,int fitnum){
			String arr[]=  orderTime.split(" ");
			  String  date=arr[0]; 
			  String  ordertime0=arr[1]; 
			  
			  SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
			  Date ordertime=null;
			  try {
				ordertime=sdf.parse(ordertime0);       //预约时间（Date）
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			  
			    Date endtime= countendtime(ordertime0,fitnum);  //结束时间（Date）
			  
			    Ordertime2 Ordertime2=new Ordertime2(date,ordertime,endtime);
			   
			 return Ordertime2;
			 
			  
		  }
		
		  
		  
		  /**
			 * 	* @方法名:计算该类型项目的结束时间
			 * 	* @参数:开始时间、项目类型
			 * 	* @输出:
			 * 	* @备注:
			 * 	* @作者: 钱程浩
			 * 	* @时间: 2018年1月29 6:42:23
			 * 	* @修改:
			 * 	*/
			public  Date countendtime(String starttime,int fitnum) {
				Fit fit0=new Fit(0,fitnum,0);
				Fit fit=ordertimeService.requiredtime(fit0);
				int requiredtime=fit.getRequiredtime();
				
				//计算结束时间
				SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
				 Date time=null;
				try {
					time = sdf.parse(starttime);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				 Calendar cal = Calendar.getInstance();
				 cal.setTime(time);
				 cal.add(Calendar.MINUTE, +requiredtime);
				  time = cal.getTime();
				  
				 return time;
				 
			}

		  
		  
		/*  public static void main(String[] args) throws ParseException {
			Date d=timeChaange("2018-1-12 15:59:38");
		    System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(d));
		   
		  
		  }
		  */
		  
		
		
		  
		  
}
